package com.jie.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jie.pojo.User;
import com.jie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 曾豪杰
 * @Date: 2022/09/12/9:38
 * @Description:
 */
@Controller
@Slf4j
@RequestMapping("/admin")
public class LoginController {
    @Autowired
    private UserService userService;

    @GetMapping
    public String getLogin(){
        return "admin/login";
    }


    @PostMapping("/login")
    public String toLogin(String username,String password, HttpSession session, RedirectAttributes redirectAttributes){
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName, username);
        //DigestUtils.md5DigestAsHex(x.getBytes()) md5
//        System.out.println(DigestUtils.md5DigestAsHex(username.getBytes()));
        queryWrapper.eq(User::getPassword,DigestUtils.md5DigestAsHex(password.getBytes()));
        User user1 = userService.getOne(queryWrapper);
        if(user1!=null){
            user1.setPassword(null);
            session.setAttribute("user",user1);
            return "admin/index";
        }else {
            redirectAttributes.addFlashAttribute("message","用户名密码错误");
            return "redirect:/admin";
        }
    }
    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute("user");
        return "redirect:/admin";
    }

 }
